<?php

namespace app\common\controller;

use app\api\controller\Auth;
use app\api\model\Agent;
use app\api\model\ServerUser;
use app\api\model\Token;
use app\api\model\User;
use app\BaseController;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\Model;
use think\Response;

/**
 * Class AdminController
 * @package app\common\controller
 */
class ApiController extends BaseController
{

    use \app\common\traits\JumpTrait;

    //token
    protected $token = '';
    //用户 id
    protected $uid = 0;

    protected $method = '';

    protected $u_type = 1;

    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录的方法
     * @var array
     */
    protected $mustLogin = [];

    protected $auth = null;

    protected $responseType = 'json';

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'status_text',
    ];

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 不导出的字段信息
     * @var array
     */
    protected $noExportFields = ['delete_time', 'update_time'];

    /**
     * 初始化方法
     */
    protected function initialize()
    {

        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,method,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
        $token = $this->request->header('token');
        $method = $this->request->header('method');

        $this->method = $method;

        $this->auth = Auth::instance();

        if (empty($method)) {
            $this->error('无权限！');
        }

        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $is_token = Token::where('token', $token)->where('type', $method)->find();
            if (!$is_token) {
                $this->error('请先登录1', null, 401);
            } else {
                $this->uid = $is_token['user_id'];
            }
            if (!$this->uid) {
                $this->error('请先登录2', null, 401);
            }
            if ($method == 'server_user') {
                $userModel = new ServerUser();
                $block = $userModel->where('id', $this->uid)->value('block');
                $this->u_type = 2;
            }
            if ($method == 'pw_user') {
                $userModel = new User();
                $block = $userModel->where('id', $this->uid)->value('status');
                $this->u_type = 1;
            }
            if ($method == 'agent_user') {
                $userModel = new Agent();
                $block = $userModel->where('id', $this->uid)->value('block');
                $this->u_type = 3;
            }
            if ($block == 2) {
                $this->error('账号冻结，请联系平台处理', null, 402);
            }

            //     // 判断是否需要验证权限
            //     if (!$this->auth->match($this->noNeedRight)) {

            //         // // 判断控制器和方法判断是否有对应权限
            //         // if (!$this->auth->check($path)) {
            //         //     $this->error('没有权限', null, 403);
            //         // }
            //         if (!$this->uid) {
            //             $this->error('没有权限', null, 403);
            //         }
            //         // $userStatus = $this->userIsExit($this->uid, $method);
            //         $userStatus = '';
            //         if (!$userStatus) {
            //             $this->error('没有权限', null, 403);
            //         }
            //         if ($userStatus['status'] != 1) {
            //             $this->error('账号异常，请联系客服处理', null, 403);
            //         }
            //         if (!$userStatus['wx_openid']) {
            //             $this->error('需要授权登录', null, 201);
            //         }
            //     }
            // } else {
            //     // 如果有传递token才验证是否登录状态
            //     if ($token) {
            //         // return false;
            //         // $this->auth->init($token);
            //     }
        }

        parent::initialize();
    }

     //判断是否是HTTPS
     function isHTTPS()
     {
         if (defined('HTTPS') && HTTPS) {
             return true;
         }
 
         if (!isset($_SERVER)) {
             return false;
         }
 
         if (!isset($_SERVER['HTTPS'])) {
             return false;
         }
 
         if ($_SERVER['HTTPS'] === 1) { //Apache
             return true;
         } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
             return true;
         } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
             return true;
         }
         return false;
     }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $data = '', array $header = [])
    {
        $code = 1;
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];

        $type = $this->getResponseType();
        $header['Access-Control-Allow-Origin'] = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token,Authorization,XX-Api-Version,XX-Wxapp-AppId';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息,若要指定错误码,可以传数组,格式为['code'=>您的错误码,'msg'=>'您的错误消息']
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($data, $code, $msg, $type, $header);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return 'json';
    }

    protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }

        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type, $code)->header($header);

        throw new HttpResponseException($response);
    }

    
     /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        // $appId = 'FSAID_131aba6';
        // $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        // $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $appId = 'FSAID_131b260';
        $appSecret = 'bc3f3bd184c54895aca794db584f36fa';
        $permanentCode = 'C4E757336822DECDBBBB2C6117ABF449';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               $zxc = Db::name('atoken')->where('id',1)->update($data);  
            }else{
               $zxc = Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }

      /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function urlhttp_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS,http_build_query($data));
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
     
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
       $content = urldecode($content);
       $cont = json_decode($content,true);
       return $cont;

   }

    /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);


       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
     
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
       
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }

   //根据员工昵称获取crm用户id
   public function getByNickName($nickName){
    $qwe = $this->corpAccessToken();
    $url ='https://open.fxiaoke.com/cgi/user/getByNickName';  // 通过员工昵称查询员工
    $corpAccessToken = $qwe['corpAccessToken'];   
    $corpId = $qwe['corpId'];
    //$mobile = "刘兴堂";
    $phone = explode(",",$nickName);
    $sdf = [];
    foreach ($phone as $nickName){
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'nickName'),JSON_UNESCAPED_UNICODE);
        $method = 'POST';
        $header = [
                        'Content-Type:application/json'
                    ];
        $dsdf = $this->http_curl($url,$method, $res, $header);
        
        if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
        {
        //$sdf[] = $dsdf['empList'][0]["openUserId"];
            $rst = [
                "code"=>1,
                "data"=>$dsdf['empList'][0]["openUserId"]

            ];
        }else{
            $rst = [
                "code"=>-1,
                "msg"=>$dsdf["errorDescription"]

            ];
        }
    }
    return $rst;
}


    //根据手机号获取crm用户id
    public function getByMobile($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByMobile';  // 根据手机号查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        $phone = explode(",",$owner_id);
        $sdf = [];
        foreach ($phone as $mobile){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'mobile'),JSON_UNESCAPED_UNICODE);
        
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            $sdf[] = $dsdf['empList'][0]["openUserId"];
            }
        }
        return $sdf;
    }

    //查询关联客户
    public function gl_customer($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/findOne';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_B9743F457C3ABD3C3FA9473741D905DE';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'AccountObj'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            return $dsdf["data"]["objectData"]["_id"];
        }else{
            return "";
        }
    }

    //查询手机号关联客户
    public function gl_phone_customer($tel){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/findOne';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_B9743F457C3ABD3C3FA9473741D905DE';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'tel','field_values'=>[$tel],'operator'=>'EQ' ]]],'dataObjectApiName'=>'AccountObj'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            if(!empty($dsdf['data'])){
                return $dsdf["data"]["objectData"]["_id"];
            }else{
                return "";
            }
            
        }else{
            return "";
        }
    }

    /**
    *   post 请求体 头部 封装
    */
    protected function qqtbff($data)
    {
        $qwe = $this->corpAccessToken();
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_B9743F457C3ABD3C3FA9473741D905DE';
        $res =  compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data');
    //   dump($res);die; 
        return $res;
    }

    /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */   
    protected function htcurl($url, $data = array())
    {
        $method = 'POST';
        $timeout = 10;
        $header = [
                        'Content-Type:application/json'
                    ];
        $curl = curl_init($url);
        $method = strtoupper($method);
        //请求方式啥
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        //post请求
        if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        //设置header头
        // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
        
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        //返回抓取数据
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, true);
        //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);

        //https请求
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $curlError = curl_error($curl);
        list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
        $status = $status;
        $headerStr = trim(substr($content, 0, $status['header_size']));
        $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
        //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

    }


    //获取视频秘钥
    public function get_video_key(){
        $uuid = "630ecdf2127490150da0df4e";
        $appkey = "319054034924c5a91562d2ed6eb85a2f";
        $appSecret = "8c3067cea3d04c89af4067cd4f9395d3";
        $timeMillis = "00000011662092293000";
        $movedCard = 7;
        $encryptStr  = $uuid.$appkey.$appSecret.$timeMillis;
    
        //字符串转化为二进制数组
        $encryptByte = $this->getBytes($encryptStr);
        $changeByte = $this->change($encryptByte, $movedCard);
        $mergeByte = $this->mergeByte($encryptByte, $changeByte);
        $mergeByte =  $this->tostr($mergeByte);
        $qwe = md5($mergeByte);
        return $qwe;
    }

    public function getBytes($string) {  
        $bytes = array();  
        for($i = 0; $i < strlen($string); $i++){  
             $bytes[] = ord($string[$i]);  
        }  
        return $bytes;  
    }

     /**
      * 简单移位
      */
      public function change($encryptByte, $movedCard){
        $encryptLength = count($encryptByte);
        $temp = "";
        for ($i = 0; $i < $encryptLength; $i++) {
            $temp = (($i % $movedCard) > (($encryptLength - $i) % $movedCard)) ? $encryptByte[$i] : $encryptByte[$encryptLength - ($i + 1)];
            $encryptByte[$i] = $encryptByte[$encryptLength - ($i + 1)];
            $encryptByte[$encryptLength - ($i + 1)] = $temp;
        }
        return $encryptByte;
    }

    /**
    * 合并
    *
    */
    public function mergeByte($encryptByte, $changeByte){
        $encryptLength = count($encryptByte);
        $encryptLength2 = $encryptLength * 2;
        $temp = array_fill(0,$encryptLength2,0);
        for ($i = 0; $i < $encryptLength; $i++) {
            $temp[$i] = $encryptByte[$i];
            $temp[$encryptLength2 - 1 - $i] = $changeByte[$i];
        }
        return $temp;
    }

     /**
     * 将字节数组转化为string类型的数据
     *  $bytes 字节数组
     *  $str 目标字符串
     *  一个string类型的数据
     */

    public static function tostr($bytes) {
        $str = '';
        foreach($bytes as $ch) {
            $str .= chr($ch);
        }
        return $str;
    }

    //AES加密
    public function aes_encryption($data){
        $phone = "test";//admin
        $pass = "123456";//woshiys321

        //获取时间戳
        // $timeMillis = $this->get_timestamp();
        $timeMillis = '00000011662092293000';
        $AppSecret ='8c3067cea3d04c89af4067cd4f9395d3';
        $key = $this->soudf($timeMillis,$AppSecret);
        $res =  openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, '');
        $encryptString = strtoupper(bin2hex($res));
        return $encryptString;
        //dump($encryptString);die;
    }

    public function soudf($timeMillis,$AppSecret)
    {
       $timeMillis = mb_substr($timeMillis,-10);
       $key = mb_substr($timeMillis.$AppSecret,0,16);
       return $key;
    }

    //获取时间戳
    public function get_timestamp(){
        $timeMillis = time().'000';
        $timeMillis = $this->getCounter().$timeMillis;   // 20位时间
        return $timeMillis;
    }

    
    /**
    * 获取计数器
    *
    * @return
    */
    public function getCounter(){
        $counter = $this->counter;
        $counter++;
        if ($counter < 10)
          return "000000".$counter;
        else if ($counter < 100)
          return "00000".$counter;
        else if ($counter < 1000)
          return "0000".$counter;
        else if ($counter < 10000)
          return "000".$counter;
        else if ($counter < 100000)
          return "00".$counter;
        else if ($counter < 1000000)
          return "0".$counter;
        else if ($counter < 10000000)
          return $counter;
        else {
          $counter = 1;
          return "000000".$counter;
        }
    }

    

}
